/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.commons.cryptography.providers;

import io.iec.edp.caf.commons.cryptography.service.SymmetricCryptoProvider;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * DES加密服务实现
 *
 * @author guowenchang
 */
@Slf4j
public class DESCryptoProvider implements SymmetricCryptoProvider {

    @Override
    public byte[] encrypt(byte[] byteIn, byte[] key, byte[] vector) {
        try {
            DESKeySpec desKey = new DESKeySpec(key);
            //创建一个密匙工厂，然后用它把DESKeySpec转换成SecretKey
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secretKey = keyFactory.generateSecret(desKey);
            //Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");

            //用密匙初始化Cipher对象,ENCRYPT_MODE用于将 Cipher 初始化为加密模式的常量
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(vector));
            //现在，获取数据并加密
            //正式执行加密操作
            return cipher.doFinal(byteIn); //按单部分操作加密或解密数据，或者结束一个多部分操作
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }

        return null;
    }

    @Override
    public byte[] decrypt(byte[] byteIn, byte[] key, byte[] vector) {
        try {
            // 创建一个DESKeySpec对象
            DESKeySpec desKey = new DESKeySpec(key);
            // 创建一个密匙工厂
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            // 将DESKeySpec对象转换成SecretKey对象
            SecretKey secretKey = keyFactory.generateSecret(desKey);
            // Cipher对象实际完成解密操作
            Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");
            // 用密匙初始化Cipher对象
            cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(vector));
            // 真正开始解密操作
            return cipher.doFinal(byteIn);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }

        return null;
    }
}
